<?php
/*==========================================================================*\
| AGRIVIET - CONTENT MANAGERMENT SYSTEM						
\*==========================================================================*/
$namedb='vietcmsc_db';
$dir= "./backup";
if(!file_exists($dir)){
@mkdir($dir);
}
$config['sortOrder'] = "nameDESC";
$config['start'] = 0;
$config['max'] = 0;
$config['rows'] = 10; // rows of images per page
$config['cols'] = 1; // columns of images per page
$config['scroll'] = 5; // max page numbers to show at once
$config['page'] = isset($_GET['page'])?$_GET['page']:"0";

/////////////////////////
function db_getDbCollation($db) {
	global $mysql;
	$return = mysql_fetch_array(mysql_query("SHOW VARIABLES LIKE 'collation_database'"));
	$return = $return[1];
	return $return;
	}
// Delete backup files in backup folder
if(isset($_GET['del'])){
unlink('backup/'.$_GET['del']);
echo "<script>window.location='./?act=backup'</script>";
}

// Delete All backup files in backup folder
if(isset($_GET['delall']) && $_GET['delall']=='yes'){
$filelist=getFileList($dir);
	foreach($filelist as $files){
	unlink($dir.'/'.$files);
	}
echo "<script>window.location='./?act=backup'</script>";	
}

/*================================ RESTORE DATABSE ============================*/
if(isset($_POST['restore'])){
$err='';
if($_POST['file']=='') $err .='Please select a file to restore!<br>';
if($err==''){
$ft=fopen("backup/".$_POST['file'],"r",1);

$gz = gzopen("backup/".$_POST['file'], 'r');
if($gz){
 while (!gzeof($gz)) {
  $restore_query .= gzgetc($gz);
 }
}
gzclose($gz);

if (isset($restore_query)) {
          $sql_array = array();
          $sql_length = strlen($restore_query);
          $pos = strpos($restore_query, ';');
          for ($i=$pos; $i<$sql_length; $i++) {
            if ($restore_query[0] == '#') {
              $restore_query = ltrim(substr($restore_query, strpos($restore_query, "\n")));
              $sql_length = strlen($restore_query);
              $i = strpos($restore_query, ';')-1;
              continue;
            }
            if ($restore_query[($i+1)] == "\n") {
              for ($j=($i+2); $j<$sql_length; $j++) {
                if (trim($restore_query[$j]) != '') {
                  $next = substr($restore_query, $j, 6);
                  if ($next[0] == '#') {
					// find out where the break position is so we can remove this line (#comment line)
                    for ($k=$j; $k<$sql_length; $k++) {
                      if ($restore_query[$k] == "\n") break;
                    }
                    $query = substr($restore_query, 0, $i+1);
                    $restore_query = substr($restore_query, $k);
					// join the query before the comment appeared, with the rest of the dump
                    $restore_query = $query . $restore_query;
                    $sql_length = strlen($restore_query);
                    $i = strpos($restore_query, ';')-1;
                    continue 2;
                  }
                  break;
                }
              }
              if ($next == '') { // get the last insert query
                $next = 'insert';
              }
              if ( (eregi('CREATE', $next)) || (eregi('INSERT', $next)) || (eregi('DROP T', $next)) ) {
                $next = '';
                $sql_array[] = substr($restore_query, 0, $i);
                $restore_query = ltrim(substr($restore_query, $i+1));
                $sql_length = strlen($restore_query);
                $i = strpos($restore_query, ';')-1;
              }
            }
          }}
		  for ($i=0, $n=sizeof($sql_array); $i<$n; $i++) {
            mysql_query($sql_array[$i]);
          }

echo "<script>window.location='./?act=backup&code=1'</script>";
 }
 echo '<div class="red">'.$err.'</div>';
}

/*================================ BACKUP DATABSE ============================*/
if(isset($_POST['butBk'])){	
	$match = mysql_fetch_array(mysql_query("SELECT VERSION()"));
	$match = explode('.', $match[0]);
	define('MYSQL_VERSION',(int) sprintf('%d%02d%02d', $match[0], $match[1], intval($match[2])));
	unset($match);
	
	define('NOW',gmmktime());
	if (MYSQL_VERSION >= 40102)	define('ENGINE_KEYWORD','ENGINE');
	else define('ENGINE_KEYWORD','TYPE');
	
	
	$result = mysql_query("SHOW TABLES FROM $namedb");
		$sql = 
		"# =========================================================\n".
		"# VIETCMS DATABASE BACKUP\n".
		"# DATE : ".date('d-m-Y  H:i:s',NOW)."\n".
		"# Created by Nguyen Van Duc 0938288852 - info@vietcms.com\n".
		"# =========================================================\n\n";
	while ($row = mysql_fetch_array($result)) {
	$table_name = $row[0];
		$q_cl = mysql_query("SHOW COLUMNS FROM `$table_name`");
		#$str = 
			#"-- --------------------------------------------------------\n".
			#"-- TABLE $table_name\n".
			#"-- --------------------------------------------------------\n\n";
		$str .= "DROP TABLE IF EXISTS `$table_name`;\n";
		$str .= "CREATE TABLE `$table_name` (\n";
		$pri_arr = array();
		$key_arr = array();
		$cl_name = '';	
		$cl_size = mysql_num_rows($q_cl);
		while ($r_cl = mysql_fetch_array($q_cl)) {
		extract($r_cl);
		$str .= "  `". $Field ."` ". $Type;
		$cl_name .= "`". $Field ."`, ";
		if ($Null && !$Default) $str .= ' default NULL';
		elseif (isset($Default)) $str .= " NOT NULL default '". $Default ."'";
		elseif (!$Null) $str .= " NOT NULL";
		if ($Extra) $str .= " auto_increment";
		$str .= ",\n";
		if ($Key == 'PRI') $pri_arr[] = $Field;
		elseif ($Key == 'MUL') $key_arr[] = $Field;
		}
		unset($Field, $Type, $Null, $Default, $Extra);
		if (count($pri_arr)) {
			$str .= " PRIMARY KEY (";
			for ($i=0;$i<count($pri_arr);$i++)	$str .= "`$pri_arr[$i]`,";
			$str = substr($str,0,-1);
			$str .= "),\n";
		}
		if (count($key_arr)) for ($i=0;$i<count($key_arr);$i++)	$str .= " KEY `$key_arr[$i]` (`$key_arr[$i]`),\n";
		$str = substr($str,0,-2);
		$r_status =mysql_fetch_array(mysql_query("SHOW TABLE STATUS LIKE '$table_name'"));
		extract($r_status);
		if (ENGINE_KEYWORD == 'ENGINE') $Type = $Engine;
		$str .= "\n) ".ENGINE_KEYWORD."=".$Type;
		if ($Auto_increment) $str .= " AUTO_INCREMENT=".$Auto_increment;
		if (MYSQL_VERSION >= 40102) {
			$collation = db_getDbCollation($db_name);
			if (strpos($collation, '_'))
				$str .= ' DEFAULT CHARACTER SET '.substr($collation, 0, strpos($collation, '_')).' COLLATE '.$collation;
			else
				$str .= ' DEFAULT CHARACTER SET '.$collation;
		}		
		#$Comment=true;
		if ($Comment) $str .= " COMMENT='".addslashes($Comment)."'";
		$str .= ";\n";
		#if (!$_POST['export_structure']) $str = '';

		$_POST['export_data']=true;
		if ($_POST['export_data']) {
			$cl_name = substr($cl_name,0,-2);
			$query = mysql_query("SELECT * FROM `$table_name`");
			if (mysql_num_rows($query)) {
				#$str .= 
					#"-- --------------------------------------------------------\n".
					#"-- TABLE $table_name's DATA\n".
					#"-- --------------------------------------------------------\n\n";
				$si = "INSERT INTO `$table_name` ($cl_name) VALUES ";
				while ($r = mysql_fetch_array($query)) {
					$si .= "(";
					for ($i=0;$i<$cl_size;$i++) $si .= "'".addslashes(stripslashes($r[$i]))."',";
					$si = substr($si,0,-1);
					$si .= "),";
				}
				$si = substr($si,0,-1);
				$si = str_replace(
					array("\n","\t","\r","'),('"),
					array("\\n","\\t","\\r","'),\n('"),
					$si);
				
				$si .= ";";
			}
			$str .= $si;
		}
		#echo $str;
		$str .= "\n";
		$sql .= $str;
		unset($si,$str);
	}
	$sql = gzencode($sql,9);
	$size = strlen($sql);
	
	
	$pathfile =$dir."/db_".$namedb.'_'.NOW.'.sql.gz';			
	$ft=fopen($pathfile,"w");	   		
	if(fwrite($ft,$sql)){
	echo "<script>window.location='./?act=backup'</script>";
	}
	/*	return true;
	else
		return false;*/

} else{ ?>
<? if($_GET['code']==1){?>
<div class="blue">Restore successfully!</div>
<? } ?>
<form method="POST" name="frmList" action="index.php">
<table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#D5E2FF" width="100%" id="AutoNumber1">
  
  <tr>
    <td height="25" colspan="5" align=left class="xtitle">Database backups </td>
    </tr>
  <tr>
    <td height="25" align=center class="title">Select</td>
    <td align=left class="title">&nbsp;Title</td>
    <td align="center" nowrap class="title">Date</td>
    <td align="center" nowrap class="title">Size</td>
    <td align="center" nowrap class="title"><a href="index.php?act=backup&amp;delall=yes" onclick="return confirm('Do you really want to delete all backup files?');">Delete All</a></td>
  </tr>
<?php
	
	$filelist=getFileList($dir);
	
	$config['start']=($config['page']*$config['cols']*$config['rows']);
	$config['max']=( ($config['page']*$config['cols']*$config['rows']) + ($config['cols']*$config['rows']) );

	if($config['max'] > count($filelist)){$config['max']=count($filelist);}
	$total_records= count($filelist);
	$page=new Page(); ///creating new instance of Class Page
	$page->set_page_data($urllink,$total_records,$config['rows'],$config['scroll'],true,true,true);
	$page->set_qry_string('act=backup');
	
	$i	= $config['start'];
	$k=0;
	while($i<$config['max']){
	$i++;
	$file =$filelist[$i-1];

	$k++;
	if ($k%2) $class="le"; else $class="chan";	   	

?>
  <tr class="<?=$class;?>">
    <td height="30" align="center" ><input name="file" type="radio" value="<?=$file;?>" /></td>
    <td align="left" >&nbsp;
	<a href="<?=$dir.'/'.$file;?>" target="_blank"><b><?=$file;?></b></a></td>
    <td align="center" >
	<?
	$date = str_replace('.sql.gz','',explode('-',$file));
	#echo date('d-m-Y', $date[1]);
	echo date('d-m-Y  H:i:s',filemtime('backup/'.$file));
	
	?>	</td>
    <td align="center" ><?=file_size('backup/'.$file);?></td>
    <td align="center" >
	<a href="index.php?act=backup&del=<?=$file;?>" onclick="return confirm('Bạn thật sự muốn xóa chứ?');">Delete</a></td>
  </tr>
<?  } 
if($total_records==0){
?>
<tr>
<td height="40" colspan="5" align="center" valign="middle" bgcolor="#FFFF99">
<b>Backup file not found!</b></td>
</tr>
<? } ?>
</table> 
<table width="100%" border="0" cellspacing="2" cellpadding="2">
        
        <tr>
          <td><input type="submit" name="butBk" value="Backup" class="button" />
            <input type="submit" name="restore" value="Restore" class="button" /></td>
          <td align="right"><div id="pagenav"><? echo $page->get_page_nav();?></div></td>
        </tr>
  </table>
<input type="hidden" name="act" value="backup">
</form>	
<? 
}
?>	